package com.swsc.xapp.offline;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.widget.Toast;

import com.swsc.xapp.R;
import com.swsc.xapp.activity.mainActivity.MainActivity;
import com.swsc.xapp.utils.ConstantUils;
import com.swsc.xapp.utils.NativeJSUtils;

import java.io.File;

public class UploadService extends Service {

    private  UploadTask uploadTask;

    private  String uploadUrl;

    private UploadListener listener = new UploadListener() {
        @Override
        public void onProgress(int progress) {
            getNotificationManager().notify(1, getNotification("上传中...", progress));
        }

        @Override
        public void onSuccess() {
            uploadTask =null;
            //上传成功后将前台服务通知关闭，并创建一个上传成功的通知
            stopForeground(true);
            getNotificationManager().notify(1, getNotification("上传完成", -1));
            Toast.makeText(UploadService.this, "上传成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            uploadTask =null;
            //上传失败后将前台服务通知关闭，并创建一个上传成功的通知
            stopForeground(true);
            getNotificationManager().notify(1, getNotification("上传失败", -1));
            Toast.makeText(UploadService.this, "上传失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPaused() {
            uploadTask = null;
            Toast.makeText(UploadService.this, "上传暂停", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCanceled() {
            uploadTask = null;
            stopForeground(true);
            Toast.makeText(UploadService.this, "上传取消", Toast.LENGTH_SHORT).show();
        }
    };

    private UploadBinder mBinder = new UploadBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class UploadBinder extends Binder {

        public void startUpload(String url){
            if(uploadTask == null){
                uploadUrl = url;
                uploadTask = new UploadTask(listener);
                uploadTask.execute(uploadUrl);
                startForeground(1,getNotification("上传中...", 0));
                Toast.makeText(UploadService.this, "上传中", Toast.LENGTH_SHORT).show();
            }
        }

        public void startUpload(String ... params){
            if(uploadTask == null){
                uploadTask = new UploadTask(listener);
                uploadTask.execute(params);
                startForeground(1,getNotification("上传中...", 0));
                Toast.makeText(UploadService.this, "上传中", Toast.LENGTH_SHORT).show();
            }
        }

        public void pauseUpload(){
            if(uploadTask != null){
                uploadTask.pauseUpload();
            }
        }

        public void cancelUpload(){
            if(uploadTask != null){
                uploadTask.cancelUpload();
            }else {
                if(uploadUrl != null){
                    //取消上传时需要将文件删除
                    String fileName = uploadUrl.substring(uploadUrl.lastIndexOf("/"));
//                    String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                    File file = new File(NativeJSUtils.BASE_DIR + fileName);
                    if(file.exists()){
                        file.delete();
                    }
                    getNotificationManager().cancel(1);
                    stopForeground(true);
                    Toast.makeText(UploadService.this, "取消", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private NotificationManager getNotificationManager(){
        final NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(ConstantUils.NOTIFY_CHANNEL_ID, "notify", importance);
//            channel.setDescription("notify");
//            channel.enableLights(true);
//            channel.setLightColor(Color.GREEN);
//            channel.enableVibration(true);
            manager.createNotificationChannel(channel);
        }
        return manager;
    }


    private Notification getNotification(String title, int progress){
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification.Builder builder = new Notification.Builder(this);
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(ConstantUils.NOTIFY_CHANNEL_ID);
        }
        if(progress > 0){
            //当进度大于0或者等于0的时候才显示上传进度
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress , false);
        }
        // 自动关闭
        builder.setAutoCancel(true);
        return builder.build();
    }
}
